package com.qf.aop;

import com.qf.annotation.IsLogin;
import com.qf.commons.JwtUtil;
import com.qf.entity.R;
import com.qf.entity.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class LoginAop {
    @Around("@annotation(com.qf.annotation.IsLogin)")
    public Object isLogin(ProceedingJoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String token = request.getParameter("token");
        String devid = request.getParameter("devid");

        User user = JwtUtil.parseToken(token, devid);

        if (user == null){
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            IsLogin isLogin = method.getAnnotation(IsLogin.class);

            if (isLogin.mustLogin()){
                return new R().setCode(R.Code.MUST_LOGIN).setMsg("请提前登录");
            }
        }

        UserLocal.setUser(user);

        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally {
            UserLocal.setUser(null);
        }

        return null;
    }
}
